const http = require('http')
const path = require('path')
const ffmpeg = require('fluent-ffmpeg')
const videoPath = path.resolve('D:\\迅雷下载\\阳光电影www.ygdy8.com.姜子牙.HD.1080p.国语中字.mkv')
const { Server } = require('socket.io')
var ffstream = null
var server = null

function ffmpegApp() {
    server = http
        .createServer((req, res) => {
            if (req.url == '/') {
                res.writeHead(200, { 'Content-Type': 'text/html' })
                res.end(`
            <video width="500" preload controls="controls" src="/play" type='video/mp4'>
            </video>`)
            } else if (req.url == '/video') {
                res.writeHead(200, { 'Content-type': 'text/html' })
                res.end(global.videoData)
            } else if (req.url == '/play') {
                createSocket()
                var command = ffmpeg(videoPath)
                    // .videoCodec('libx264')
                    // .audioCodec('libmp3lame')
                    // .size('320x240')
                    .format('mp4')
                    .seekInput(0)
                    .outputOptions('-movflags', 'frag_keyframe+empty_moov')
                    .on('codecData', function(data) {
                        console.log(data)
                        global.videoData = JSON.stringify(data)
                    })
                    .on('error', function(err) {
                        console.log('An error occurred: ' + err.message)
                    })
                    .on('end', function() {
                        console.log('Processing finished !')
                    })
                ffstream = command.pipe()
                ffstream.pipe(res)
            }
        })
        .listen(3666, () => {
            console.log('ffmpegApp start port 3666')
        })
}

function createSocket() {
    const io = new Server(server)
    io.on('connection', (socket) => {
        console.log('a user connected')
        if (ffstream) {
            ffstream.on('data', function(chunk) {
                // console.log('ffmpeg just wrote ' + chunk.length + ' bytes')
                socket.emit('videoInfo', chunk.length / 1024)
            })
        }
        socket.on('disconnect', () => {
            console.log('user disconnected')
        })
    })
}

ffmpegApp()
